<template>
	<div id="AwakeBB">
		<div v-if="isOrder" style="margin: 1vm;">
			<el-form :inline="true" :model="searchform" class="form" v-loading="searchLoading" style="padding-left: 10px;">
				<el-form-item label="">
					<el-input :size="btnsize" v-model="searchform.name" placeholder="名称"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button :size="btnsize" type="primary" @click="onSearch">查询</el-button>
				</el-form-item>
			</el-form>
			<el-container class="outerContainer" v-if="spineList.length === 0" style="text-align: center;">
				<el-header style="margin: 0px;height: auto;">
					立绘召集中...
				</el-header>
				<el-main style="margin: 0px;height: auto;">
					<el-image style="width: 100px; height: 100px" :src="loadImg">
					</el-image>
				</el-main>
			</el-container>
			<el-row v-else>
				<el-col :span="attributesSpan" v-for="(item,index) in spineList" :key="item.id">
					<div v-on:click="getSpine(item)" class="outerContainer">
						{{ item.chineseName }}
					</div>
				</el-col>
			</el-row>
			<br/>
			<div class="block" v-if="isMobile">
				<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
					:current-page="currentPage" :page-sizes="[5, 10, 20, 30]" :page-size="pageSize" :pager-count="5"
					layout="prev, pager, next" :total="total">
				</el-pagination>
			</div>
			<div class="block" v-else>
				<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
					:current-page="currentPage" :page-sizes="[20, 30, 40, 50, 60]" :page-size="pageSize" :pager-count="11"
					layout="total, sizes, prev, pager, next, jumper" :total="total">
				</el-pagination>
			</div>
		</div>
		
		<div v-if="!isOrder">
			tips:点击播放器右下角，全屏观感更佳~<br/>
		</div>
		<el-button v-if="!isOrder" :size="btnsize" v-on:click="returnOrder"  type="primary" icon="el-icon-back" plain>
			{{ item.chineseName }} 
		</el-button> 
		<el-autocomplete v-if="!isOrder" :size="btnsize" v-model="bgcolor" :fetch-suggestions="colorSearch" 
			@select="handleSelect" @blur="setbgColor" placeholder="输入颜色代码, 如#000000">
			<template slot="prepend">背景色</template>
			<template slot-scope="{ item }">
				<div :style="{'color': item.value}">
					{{ item.value }} （{{ item.desc }})
				</div>
			</template>
		</el-autocomplete>
		<div id="player"></div>
	</div>
</template>

<script>
	import {
		yiyuziApi
	} from '@/api/yiyuziApi';

	export default {
		name: 'AwakeBB',
		components: {},
		data() {
			return {
				spineList: [],
				isOrder: true,
				attributesSpan: 6,
				isMobile: false,
				currentPage: 1,
				pageSize: 10,
				total: 0,
				searchform: {
					name: ''
				},
				loadImg: '',
				errorImg: require("@/assets/error.png"),
				thisSpine:[],
				updateLoading:false,
				searchLoading:false,
				item:{'chineseName':"","id":0},
				btnsize: "mini",
				bgcolorBefore: "#000000",
				bgcolor: "#000000",
				roleNameList: [
					'琪亚娜',
					'雷电芽衣',
					'布洛妮娅·扎伊切克',
					'无量塔姬子',
					'德丽莎·阿波卡利斯',
					'希儿·芙乐艾',
					'杏·玛尔',
					'蓬莱寺九霄',
					'伊瑟琳·利维休斯',
					'符华',
					'无色辉火',
					'西琳',
					'丽塔',
					'宁蒂',
					'迦娜',
					'芙兰',
					'神格觉醒',
					'使魔觉醒',
					'联动',
					'全屏'
				],
				colorList: [
					{"value": "#000000", "desc": "纯黑"}, 
					{"value": "#ffffff", "desc": "纯白"},
					{"value": "#f8f4ed", "desc": "汉白玉"}, 
					{"value": "#b7ae8f", "desc": "月灰"},
					{"value": "#a4aca7", "desc": "冰山蓝"},
					{"value": "#fba414", "desc": "淡橘橙"},
					{"value": "#96c24e", "desc": "芽绿"},
					{"value": "#5dbe8a", "desc": "蔻梢绿"},
					{"value": "#29b7cb", "desc": "蔚蓝"},
					{"value": "#b0d5df", "desc": "湖蓝"},
					{"value": "#66a9c9", "desc": "涧石蓝"},
					{"value": "#ccccd6", "desc": "远山紫"},
				],
			}
		},
		mounted() {
			this._isMobile();
			this.getSpineList();
			this.handleColors();
		},
		methods: {
			async getSpineList() {
				try {
					// this.searchLoading = true;
					let result = await yiyuziApi.getSpineList(this.currentPage, this.pageSize);
					console.info(result);
					this.spineList = result.data.data.list;
					this.total = result.data.data.total;
					// this.searchLoading = false;
				} catch (e) {
					console.error(e);
				}
			},

			getSpine(item) {
				let fatherId = item.id;
				this.isOrder = false;
				this.item = item;

				const atlas = yiyuziApi.getSpineUrl(fatherId, "atlas");
				const skel = yiyuziApi.getSpineUrl(fatherId, "skel");

				// document.getElementById("AwakeBB").appendChild();
				new spine.SpinePlayer("player", {
					skelUrl: skel,
					atlasUrl: atlas,
					backgroundColor: this.bgcolor,
				})
			},
			
			removePlayer() {
				document.getElementById("player").innerHTML = "";
			},

			returnOrder() {
				this.isOrder = true;
				// 清空div内的子元素
				this.removePlayer();
			},
			
			handleSizeChange(val) {
				// console.log(`每页 ${val} 条`);
				this.pageSize = val;
				this.getSpineList();
			},
			handleCurrentChange(val) {
				// console.log(`当前页: ${val}`);
				this.currentPage = val;
				this.getSpineList();
			},
			
			async onSearch() {
				try {
					let str = this.searchform.name.replace(/(^\s*)|(\s*$)/g, '');//去除空格;
					if (str != null && str != "" && str != undefined && str != "_"){
						this.searchLoading = true;
						let result = await yiyuziApi.getSpineListByNameAndPage("1", "300", str);
						this.spineList = result.data.data.list;
						this.total = result.data.data.total;
						this.currentPage = 1;
						this.searchLoading = false;
					} else {
						this.getSpineList();
					}
				} catch (e) {
					console.error(e);
				}
			},
			
			colorSearch(queryString, cb) {
				var colorList = this.colorList;
				var results = queryString ? colorList.filter(this.createFilter(queryString)) : colorList;
				// 调用 callback 返回建议列表的数据
				cb(results);
			},
			
			createFilter(queryString) {
				return (item) => {
					return (item.value.toLowerCase().indexOf(queryString.toLowerCase()) >= 0) || 
						(item.desc.indexOf(queryString) >= 0);
				};
			},
			
			handleSelect(item) {
				this.setbgColor();
			},
			
			setbgColor() {
				let color = this.bgcolor;
				if (color != null && color != "" && color != undefined && color != this.bgcolorBefore){
					var pattern = /^#[0-9a-fA-F]{6}$/;
					if(color.match(pattern) != null){
						this.removePlayer();
						this.getSpine(this.item);
						this.bgcolorBefore = color;
					}else{
						this.bgcolor = null;
						this.bgcolorBefore = null;
					}
				}
			},

			_isMobile() {
				this.isMobile = navigator.userAgent.match(
					/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i
				);
				this.pageSize = this.isMobile ? 10 : 40;
				this.attributesSpan = this.isMobile ? 24 : 6;
				this.btnsize = this.isMobile ? "mini" : "";
			},
			
			rgb2hsv (rgb) {
				var r = rgb[0]/255, g = rgb[1]/255, b = rgb[2]/255;
				var max = Math.max(r, g, b), min = Math.min(r, g, b);
				var h, s, v = max;

				var d = max - min;
				s = max == 0 ? 0 : d / max;

				if(max == min){
					h = 0;
				}else{
					switch(max){
					case r: h = (g - b) / d + (g < b ? 6 : 0); break;
					case g: h = (b - r) / d + 2; break;
					case b: h = (r - g) / d + 4; break;
					}
					h /= 6;
				}
			
				return [h, s, v];
			},

			
			handleColors() {
				var colorsArray = require('../../../public/js/colors.json');
				let _this = this;
			
				colorsArray.sort(function(a, b){
					if (_this.rgb2hsv(a.RGB)[0] === _this.rgb2hsv(b.RGB)[0])
						return _this.rgb2hsv(b.RGB)[1] - _this.rgb2hsv(a.RGB)[1];
					else
						return _this.rgb2hsv(b.RGB)[0] - _this.rgb2hsv(a.RGB)[0];
				});
				
				this.colorList = [
					{"value": "#000000", "desc": "纯黑"},
					{"value": "#ffffff", "desc": "纯白"}
				];
				colorsArray.forEach(function (color, i) {
					if (i%10 === 0){
						_this.colorList.push({"value": color.hex, "desc": color.name})
					}
				});
			},
		}
	}
</script>

<style scoped>
	#AwakeBB {
		
	}
	
	.outerContainer {
		box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);
		color: #333;
		background-color: #ffffff;
		border-radius: 10px;
		padding: 5px;
		margin: 10px;
		margin-bottom: 10px;
		font-size: 2vh;
	}
	
	.outerContainer:hover {
		background-color: #409eff;
		color: #ffffff;
		cursor: pointer;
	}
	
	/* 图片置灰 */
	.gray { 
	    -webkit-filter: grayscale(100%);
	    -moz-filter: grayscale(100%);
	    -ms-filter: grayscale(100%);
	    -o-filter: grayscale(100%);
	    filter: grayscale(100%);
	    filter: gray;
	    opacity:0.7;
	}
</style>
